<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\Ali\Controllers;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\ali\model\TodayNiceGoods;
use Doraemon\tools\ImgUrl;
use Biz\model\wiki\Wiki;


class TodayNiceGoodsController extends Controller
{
    const PAGE_SIZE = 20;


    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 今日好物展示
     * @param Content $content
     * @return Content
     */
    public function list(Request $request,Content $content)
    {
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $params['per_page'] = $page_size;
        $where = $this->_getWhere($params);
        $list = TodayNiceGoods::getListByWhere($where) ? : [];
        unset($where['LIMIT']);
        $count = TodayNiceGoods::count($where);
        $list = $this->formatList($list);
        $gridModel = new pGridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $keywordsGrid = Admin::grid($gridModel, function (Grid $grid) use($gridModel){
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                // 在这里添加字段过滤器
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('wiki_id', '商品Id')->placeholder('商品Id');
                    $filter->equal('status', '活动状态')->select(TodayNiceGoods::STATUS_ARR);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('start_time', '上线时间')->date();
                });
                $filter->expand();
            });
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->column('id');
            $grid->column('title', '标题')->width(80);
            $grid->column('sec_title', '副标题')->width(80);
            $grid->column('wiki_id', '商品Id')->width(80);
            $grid->column('wiki_img', '商品图片')->display(function() {
                return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $this->wiki_img, ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG)."' width=100 />";
            })->width(350);
            $grid->column("start_time" , '上线时间')->width(80);
            $grid->column('status', '状态')->using(
                TodayNiceGoods::STATUS_ARR
                , '删除')->label([
                12 => 'success',
                9 => 'info',
                11 => 'warning',
                13 => 'danger',
            ]);
            $grid->actions(function ($action) {
                if($action->row->status == TodayNiceGoods::STATUS_END ){
                    $action->disableEdit();
                }
            });

        });
        return $content->header('今日好物')->row($keywordsGrid);
    }

    //提示信息添加页面
    public function edit(Request $request,Content $content, $id = 0)
    {

        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('')
                ->breadcrumb(
                    ['text' => '', 'url' => '/ali/todaynicegoods/index'],
                    ['text' => '添加今日好物', 'url' => '/ali/todaynicegoods/index/create']
                )
                ->body(self::editAction($request, $id , True));
        } else {
            return $content
                ->header('今日好物列表')
                ->breadcrumb(
                    ['text' => '今日好物', 'url' => '/ali/todaynicegoods/index'],
                    ['text' => '修改今日好物', 'url' => '/ali/todaynicegoods/index/'.$id.'/edit']
                )
                ->body(self::editAction($request, $id, False));
        }
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            $data = TodayNiceGoods::get("*",['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }
        $form->text('wiki_id', '商品id')->required('不能为空');
        $form->text('title', '标题')->required('不能为空');
        $form->text('sec_title', '副标题')->required('不能为空');
        $form->imgUpload('wiki_img', '商品图', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->help("仅支持一张图片上传，小于500k");

        $form->imgUpload('back_img', '背景图片', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->help("仅支持一张图片上传，小于2M");

        $form->imgUpload('stand_img', '展台图片', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->help("仅支持一张图片上传，小于2M");
        $form->text('tags', '亮点')->help("多个用英文逗号,隔开最多3个。单个亮点字数限制7个");

     if(  $data['end_time'] && strtotime($data['end_time']) < time() ){
         $form->date('start_time', '开始时间')->default(date("Y-m-d 00:00:00"))->disable();
     }else{
         $form->date('start_time', '开始时间')->default(date("Y-m-d 00:00:00"))->required();
     }


        $form->action('/admin/ali/todaynicegoods/save');
        return $form->render();
    }



    //添加、修改提交
    public function editSubmit(Request $request)
    {
        try{
            $request = $request->all();
            //更新
            if (isset($request['id']) && $request['id']) {
                $info = TodayNiceGoods::get("*" ,['id' => $request['id']]);
                if (!$info) {
                    throw new \Exception('该活动不存在！');
                }
                $start_time = isset($request["start_time"]) ? date('Y-m-d 00:00:00', strtotime($request["start_time"])) : $info['start_time'];
            } else {
                $start_time = $request["start_time"] ? date('Y-m-d 00:00:00', strtotime($request["start_time"])) : date("Y-m-d 00:00:00");
            }

            $tags = $request["tags"] ? str_replace("，", ",", trim($request["tags"])) : '';
            if ($tags) {
                $tags = $tags ? explode(',', $tags) : [];
                foreach ($tags as $tag) {
                    if (mb_strlen($tag) > 7) {
                        throw new \Exception('亮点字符不能超过7个');
                    }
                }
                //亮点数量
                $count = count($tags);
                if ($count > 3) {
                    throw new \Exception('亮点不能超过三个');
                }
            }
            $wiki_id =  $request['wiki_id'];
            $wiki_info = Wiki::getInfoByWikiId($wiki_id);
            if (!$wiki_info) {
                throw new \Exception('商品不存在');
            }
            if($wiki_info['channel'] != Wiki::CHANNEL_TAOBAO ){
                throw new \Exception('商品不是淘宝');
            }
            $channel_spu_id = $wiki_info['channel_spu_id'];
            $data = [
                'wiki_id' => $request['wiki_id'],
                'channel_spu_id' =>$channel_spu_id,
                'title' => $request['title'],
                'sec_title' =>$request['sec_title'],
                'wiki_img' => $request['wiki_img'],
                'back_img' => $request['back_img'],
                'stand_img' => $request['stand_img'],
                'start_time' => $start_time,
                "end_time" => date('Y-m-d 23:59:59', strtotime($start_time)),
                "month" => date('Y-m', strtotime($start_time)) ?: date('Y-m', time()),
                'tags' =>  $request['tags'],
                'show_status' => TodayNiceGoods::STATUS_NORMAL,
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id,
            ];
            if(isset($request['id'])) {
                $timeGoods = TodayNiceGoods::get("*" ,['start_time' => $start_time ,'id[!]'=>$request['id'],'show_status'=> TodayNiceGoods::STATUS_NORMAL ]);
                if($timeGoods){
                    throw new \Exception('此时间段内有好物');
                }
                $rs = TodayNiceGoods::updateByWhere($data,['id' =>$request['id'] ]);
                if($rs) {
                    $success = new MessageBag([
                        'title' => '修改成功'
                    ]);
                    return redirect('/admin/ali/todaynicegoods/index')->with(compact('success'));
                } else {
                    $error = new MessageBag([
                        'title' => '修改失败'
                    ]);
                    return redirect('/admin/ali/todaynicegoods/index')->with(compact('error'));
                }
            } else {
                $timeGoods = TodayNiceGoods::get("*" ,['start_time' => $start_time , 'show_status'=> TodayNiceGoods::STATUS_NORMAL]);
                if($timeGoods){
                    throw new \Exception('此时间段内有好物');
                }

                $data['addtime'] = date("Y-m-d H:i:s" , time());
                $rs = TodayNiceGoods::insert($data);
                if($rs) {
                    $success = new MessageBag([
                        'title' => '添加成功'
                    ]);
                    return redirect('/admin/ali/todaynicegoods/index')->with(compact('success'));
                } else {
                    $error = new MessageBag([
                        'title' => '添加失败'
                    ]);
                    return redirect('/admin/ali/todaynicegoods/index')->with(compact('error'));
                }
            }

        }catch (\Exception $e) {
            $error = new MessageBag([
            'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }

    }

    //删除
    public function del($id = 0)
    {
        $info = TodayNiceGoods::get("*",['id' => $id]);
        if($info) {
            $data = [
                'show_status' => TodayNiceGoods::STATUS_DELETE,
                'edittime' => date('Y-m-d H:i:s', time()),
                'admin_id' => Admin::user()->id
            ];
            $rs = TodayNiceGoods::updateByWhere($data, ['id' => $id]);
            if($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        }

    }


    /**
     * 增加活动虚拟状态
     * @param $list
     * @return array
     */
    public  function formatList($list): array
    {
        $now = time();
        foreach ($list as &$info) {
            if (isset($info['start_time'], $info['end_time'], $info['show_status'])) {
                $start_at = strtotime($info['start_time']);
                $end_at = strtotime($info['end_time']);
                if ((int)$info['show_status'] === TodayNiceGoods::STATUS_NORMAL) {
                    if ($start_at <= $now && $end_at > $now) {
                        $info['status'] = TodayNiceGoods::STATUS_ACTING; //活动中
                    } else if ($end_at <= $now) {
                        $info['status'] = TodayNiceGoods::STATUS_END; //活动结束
                    } else if ($start_at >= $now) {
                        $info['status'] = TodayNiceGoods::STATUS_WAIT; //未开始
                    }
                }
                $act_status_arr = TodayNiceGoods::STATUS_ARR;
                $info['status_name'] = $act_status_arr[$info['status']];
            }
            if (isset($info['tags'])) {
                $info['tags_list'] = !empty($info['tags']) ? explode(",", $info['tags']) : [];
            }
            if (isset($info['end_at']) && $info['end_at']) {
                $info['date'] = date("m/d", strtotime($info['end_at']));
                $info['date_time'] = strtotime($info['end_at']);
            }
        }
        return $list;
    }


    /**
     * 获取查询条件
     * @param $params
     * @return array
     */
    private function _getWhere($params): array
    {
        $id = $params['id'] ?? 0;
        $wiki_id = $params['wiki_id'] ?? 0;
        $page = $params['page'] ?? 1;
        $page_size = $params['per_page'] ?? 20;;
        $start_time = $params['start_time'] ? date('Y-m-d H:i:s', strtotime($params['start_time'])) : 0;
        $status = $params['status'] ?? "";
        if ($id) {
            $where['id'] = $id;
        }
        if ($wiki_id) {
            $where['wiki_id'] = $wiki_id;
        }

        if ($start_time) {
            $where['start_time'] = $start_time;
        }
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        if ($status) {
            //活动中
            if ((int)$status === TodayNiceGoods::STATUS_ACTING) {
                $status = TodayNiceGoods::STATUS_NORMAL;
                $where['start_time[<=]'] = date('Y-m-d H:i:s');
                $where['end_time[>]'] = date('Y-m-d H:i:s');
            }
            //活动结束
            if ((int)$status === TodayNiceGoods::STATUS_END) {
                $where['end_time[<]'] = date('Y-m-d H:i:s');
                $status = TodayNiceGoods::STATUS_NORMAL;
            }
            //待开始
            if ((int)$status === TodayNiceGoods::STATUS_WAIT) {
                $where['start_time[>]'] = date('Y-m-d H:i:s');
                $status = TodayNiceGoods::STATUS_NORMAL;
            }
            //删除
            if ((int)$status === TodayNiceGoods::STATUS_DELETE) {
                $status = TodayNiceGoods::STATUS_DELETE;
            }
            $where['show_status'] = $status;
        }
        $where['ORDER'] = [
            'start_time' => 'DESC',
        ];
        return $where;
    }



}
